<template>
  <view>
    <uv-popup ref="popupRef" mode="center" round="20" @maskClick="closeDialog">
      <view class="ask-dialog">
        <view class="top">
          <view class="dialog-title">需求问卷</view>
          <view>
            <view class="mt-[10px]">
              <text class="label">姓名</text>
              <Custom-input
                v-model="baseForm.username"
                type="input"
                required
                :red-border="redline"
                :disabled="disabled"
              />
            </view>
            <view class="mt-[10px]">
              <text class="label">
                联系方式 <text style="font-size: 26rpx">(微信/手机)</text>
              </text>
              <Custom-input
                v-model="baseForm.phone"
                type="input"
                required
                :red-border="redline"
                :disabled="disabled"
              />
            </view>
            <view class="mt-[10px]">
              <text class="label">定制类型</text>
              <Custom-input
                v-model="baseForm.dingzhi_type"
                type="select"
                :options="customTypes"
                required
                :red-border="redline"
                key-value="value"
                key-name="label"
                :disabled="disabled"
                placeholder="请选择..."
                @change="changeDingzhiType"
              />
            </view>
            <view class="form-tip mt-[10px]" v-if="baseForm.dingzhi_type == 1">
              平台现有18款酒体均为各个品酒师对标市面畅销产品酒体调制，建议联系客服告知对标酒体，如现有酒体无匹配，可选全新定制。
            </view>
            <view class="form-tip mt-[10px]" v-else>
              为了获得最佳口感体验及缩短酒体设计周期，强烈建议在现有18款酒体或自行调制酒体基础上优化调整。
            </view>
            <view v-if="baseForm.dingzhi_type == 2" class="mt-[10px]">
              <text class="label"> 请选择酒体订单 </text>
              <Custom-input
                v-model="baseForm.dingzhi_order_sn"
                type="url"
                suffix="选择"
                prefix="订单编号"
                required
                :red-border="redline"
                :disabled="disabled"
                path="/addon/shop/pages/select/water?type=design"
                placeholder="请选择..."
              />
            </view>
            <view v-if="baseForm.dingzhi_type == 3" class="mt-[10px]">
              <text class="label"> 是否优化 </text>
              <Custom-input
                v-model="baseForm.is_needs_questionnaire"
                type="select"
                :options="[
                  { label: '否', value: 0 },
                  { label: '是', value: 1 },
                ]"
                required
                :red-border="redline"
                key-value="value"
                key-name="label"
                :disabled="disabled"
                placeholder="请选择..."
              />
            </view>
          </view>
        </view>

        <!-- 手风琴列表 -->
        <up-collapse ref="collapseRef" :value="collapseValue">
          <up-collapse-item v-if="baseForm.dingzhi_type == 1" name="1">
            <template #title>
              <text class="collapse-title">酒体风格</text>
            </template>
            <Custom-section type="flavor" :form="customForm" :disabled="disabled" />
          </up-collapse-item>
          <up-collapse-item v-if="baseForm.dingzhi_type == 1" name="2">
            <template #title>
              <text class="collapse-title">品鉴细化</text>
            </template>
            <Custom-section type="tasting" :form="customForm" :disabled="disabled" />
          </up-collapse-item>
          <up-collapse-item
            v-if="
              baseForm.dingzhi_type == 2 ||
              (baseForm.dingzhi_type == 3 && baseForm.is_needs_questionnaire == 1)
            "
            name="3"
          >
            <template #title>
              <text class="collapse-title">优化方向</text>
            </template>
            <Custom-section
              type="optimizeDirection"
              :form="optimizeForm"
              :disabled="disabled"
            />
          </up-collapse-item>
          <up-collapse-item
            v-if="
              (baseForm.dingzhi_type == 2 ||
              (baseForm.dingzhi_type == 3 && baseForm.is_needs_questionnaire == 1) ) && 
              optimizeForm?.direction
            "
            name="4"
          >
            <template #title>
              <text class="collapse-title">优化细化</text>
            </template>
            <Custom-section
              type="optimizeDetail"
              :form="optimizeForm"
              :disabled="disabled"
            />
          </up-collapse-item>
          <up-collapse-item
            v-if="
              [1, 2].includes(baseForm.dingzhi_type) ||
              (baseForm.dingzhi_type == 3 && baseForm.is_needs_questionnaire == 1)
            "
            name="5"
          >
            <template #title>
              <text class="collapse-title">饮用场景与特殊需求</text>
            </template>
            <Custom-section type="scene" :form="sceneForm" :disabled="disabled" />
          </up-collapse-item>
          <up-collapse-item name="6">
            <template #title>
              <text class="collapse-title">定制服务说明</text>
            </template>
            <view class="accordion-content">
              <view class="form-tip" style="margin-bottom: 20rpx">
                您选择的是【专家私人酒体设计】，支付预付金并提交定制需求后，客服将在3个工作日内联系您确认细节，后续客服将根据您提供的酒体需求与专家最终酒体报价修改订单金额,请您关注订单后续信息并及时补足酒体尾款，生成私人酒体定制订单。
              </view>

              <view class="mt-[10px]">
                <text class="label">选择专家</text>
                <view class="flex items-center justify-between mt-[10px]">
                  <picker
                    v-if="!disabled"
                    :range="expertList.map((i: any) => i.name)"
                    :value="expertIdx"
                    @change="expertChange"
                    @cancel="blurInput"
                  >
                    <view class="picker-disabled" :class="{ redline }">
                      {{ expertList[expertIdx]?.name || "请选择" }}
                    </view>
                  </picker>
                  <view v-if="disabled" class="picker-disabled">
                    {{ expertList[expertIdx]?.name || "请选择" }}
                  </view>
                  <up-image
                    v-if="baseForm.bartender_id"
                    :src="expertAvatar"
                    mode="aspectFill"
                    width="210rpx"
                    height="152rpx"
                    radius="20rpx"
                    class="ml-[20rpx]"
                  >
                  <template #error>
                    <image src="../../../../static/baocai.png" mode="scaleToFill" style="width: 210rpx; height: 152rpx" />
                  </template>
                </up-image>
                </view>
              </view>
              <view class="mt-[10px]">
                <text class="label" style="font-size: 29rpx">预付总金额</text>
                <text style="color: #e43d33; font-size: 29rpx">￥</text>
                <text style="color: #e43d33; font-size: 38rpx">
                  {{ parseFloat(baseForm.price).toFixed(2) }}
                </text>
              </view>
              <view class="mt-[10px]">
                <text class="label">酒体交付周期期望</text>
                <Custom-input
                  v-model="baseForm.deliver_day"
                  type="input"
                  suffix="天内"
                  :disabled="disabled"
                />
              </view>
              <view class="mt-[10px]">
                <text class="label">是否需定制包装设计</text>
                <Custom-input
                  v-model="baseForm.dingzhi_bz_sj"
                  type="select"
                  :options="[
                    { label: '否', value: 0 },
                    { label: '是', value: 1 },
                  ]"
                  key-value="value"
                  key-name="label"
                  :disabled="disabled"
                  placeholder="请选择..."
                />
              </view>
              <view v-if="!disabled" class="mt-[20px]">
                <view class="label mb-[10px]">授权与确认</view>
                <up-checkbox
                  v-model:checked="baseForm.authChecked"
                  :label="`我理解专家可能根据技术可行性对需求进行\n微调，并向我最终方案确认前沟通调整。`"
                  name="agree"
                  used-alone
                  label-size="26rpx"
                  label-color="#999"
                  active-color="red"
                  shape="circle"
                />
              </view>
              <button
                v-if="!disabled"
                class="submit-btn"
                :disabled="!baseForm.authChecked"
                @click="handleSubmit"
              >
                提交
              </button>
            </view>
          </up-collapse-item>
        </up-collapse>
      </view>
    </uv-popup>
  </view>
</template>

<script lang="ts" setup>
import { computed, nextTick, ref, watch } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import CustomInput from "./CustomInput.vue";
import CustomSection from "@/addon/shop/components/ask/CustomSection.vue";
import { img } from "@/utils/common";
import { getBartender } from "@/addon/shop/api/select";

const popupRef = ref<any>(null);
const props = defineProps({
  disabled: {
    // 是否禁用
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["complete"]);

const redline = ref<boolean>(false); // 是否显示红色边框
const collapseValue = ref<any>([]); // 默认展开
const collapseRef = ref<any>(null); // 折叠面板
const baseForm = ref<any>({
  username: null, // 姓名
  phone: null, // 联系方式
  dingzhi_type: null, // 定制类型
  dingzhi_order_sn: null, // 酒体定制订单编号
  dingzhi_order_id: null, // 酒体定制订单id
  is_needs_questionnaire: null, // 调优
  bartender_id: null, // 专家id
  price: 0, // 预付金金额
  deliver_day: 30, // 交付周期
  dingzhi_bz_sj: null, // 是否定制包装设计
  authChecked: false, // 是否同意授权
});
const customTypes = ref([
  { label: "全新定制", value: 1 },
  { label: "基于现有酒体优化", value: 2 },
  { label: "自行寄样对标调制", value: 3 },
]);

const customForm = ref({
  // 酒体风格------------------
  aromaType: null, // 香型
  alcoholRange: null, // 酒精度期望范围
  taste: null, // 口感偏好
  flavour: null, // 风味关键词
  priceRange: null, // 价格区间
  // 品鉴细化------------------
  intensity: null, // 强度偏好
  layer: null, // 层次感
  comfort: null, // 幽雅馥郁舒适突出
  demand: null, // 特别要求
  lips: null, // 入口感受
  lipsTaste: null, // 甜/苦/酸平衡
  tasteStrength: null, // 喷香强度
  richFeel: null, // 醇厚丰满感受
  harmoniousFeel: null, // 谐调圆润感受
  sustain: null, // 持续时间
  aftertaste: null, // 回味倾向
  personality: null, // 酒体个性
  drunkSpeed: null, // 醉酒速度
  wakeSpeed: null, // 醒酒速度
  complexity: null, // 复杂度
  balance: null, // 平衡度偏好
});

const optimizeForm = ref({
  // 优化方向------------------
  direction: null, // 优化方向
  remark: null, // 其他调整说明
  priceRange: null, // 价格区间
  // 优化细化------------------
  alcoholRange: null, // 酒精度期望范围
  intensity: null, // 强度偏好
  layer: null, // 层次感
  comfort: null, // 幽雅馥郁舒适突出
  demand: null, // 特别要求
  lips: null, // 入口感受
  lipsTaste: null, // 甜/苦/酸平衡
  tasteStrength: null, // 喷香强度
  sustain: null, // 持续时间
  aftertaste: null, // 回味倾向
});

const sceneForm = ref({
  scene: null, // 主要饮用场景
  quantity: null, // 预计需求量
  specialNeeds: null, // 特殊需求
});

const expertIdx = ref(-1); // 专家下标

// 专家头像
const expertAvatar = computed(() => {
  let row = <any>expertList.value.find((i: any) => i.id == baseForm.value.bartender_id);
  return row ? img(row.avatar) : "";
});

const expertList = ref<any>([]); // 专家列表

watch(() => optimizeForm.value.direction, (val: any) => {
  if (!val.includes('酒精度调整')) {
    optimizeForm.value.alcoholRange = null;
  }
  if (!val.includes('香气调整')) {
    optimizeForm.value.intensity = null;
    optimizeForm.value.layer = null;
    optimizeForm.value.comfort = null;
    optimizeForm.value.demand = null;
  }
  if (!val.includes('口感调整')) {
    optimizeForm.value.lips = null;
    optimizeForm.value.lipsTaste = null;
    optimizeForm.value.tasteStrength = null;
  }
  if (!val.includes('余味调整')) {
    optimizeForm.value.sustain = null;
    optimizeForm.value.aftertaste = null;
  }
  collapseValue.value = ["1", "2", "3", "5", "6"];
  setTimeout(() => {
    collapseValue.value = ["1", "2", "3", "4", "5", "6"];
  }, 800);
})

onLoad(() => {
  uni.$on("chooseOrder", (order: any) => {
    nextTick(() => {
      baseForm.value.dingzhi_order_sn = order.order_no;
      baseForm.value.dingzhi_order_id = order.order_id;
    });
  });
});

// 获取专家列表
const getExpertList = () => {
  getBartender({ page: 1, limit: 120 }).then((res: any) => {
    expertList.value = res.data.data;
    expertIdx.value = expertList.value.findIndex(
      (i: any) => i.id == baseForm.value.bartender_id
    );
  });
};

// 专家选择
const expertChange = (e: any) => {
  expertIdx.value = e.detail.value;
  baseForm.value.bartender_id = expertList.value[e.detail.value].id;
  blurInput();
};

// 失去焦点
const blurInput = () => {
  const val = baseForm.value.bartender_id;
  if (val == "" || val == null) {
    redline.value = true;
  } else {
    redline.value = false;
  }
};

// 打开弹窗
const openDialog = (data: any) => {
  uni.removeStorageSync("chooseOrder");
  if (props.disabled) {
    baseForm.value = data.baseForm;
    customForm.value = data.customForm;
    optimizeForm.value = data.optimizeForm;
    sceneForm.value = data.sceneForm;
  } else {
    baseForm.value.price = data.price;
    baseForm.value.bartender_id = data.bartender_id;
    console.log(data);
  }
  getExpertList();
  setTimeout(() => {
    collapseValue.value = ["1", "2", "3", "4", "5", "6"];
  }, 800);
  popupRef.value.open();
};

// 定制类型改变重新计算折叠面板高度
const changeDingzhiType = () => {
  nextTick(() => {
    collapseRef.value.init();
  });
};

// 关闭弹窗
const closeDialog = () => {
  emit("complete", {
    finish: validate(),
    bartender_id: baseForm.value.bartender_id,
  });
  popupRef.value.close();
};

// 提交表单
const handleSubmit = () => {
  console.log(
    "提交表单",
    baseForm.value,
    customForm.value,
    optimizeForm.value,
    sceneForm.value
  );
  if (!baseForm.value.authChecked) {
    uni.showToast({ title: "请先同意授权与确认", icon: "none" });
    return;
  }
  if (!validate()) {
    blurInput();
    uni.showToast({ title: "请完善表单", icon: "none" });
    return;
  }
  emit("complete", {
    baseForm: baseForm.value,
    customForm: customForm.value,
    optimizeForm: optimizeForm.value,
    sceneForm: sceneForm.value,
    finish: true,
  });
  popupRef.value.close();
};

// 校验字段是否填写完成
const validate = () => {
  let flag = true;
  const {
    username,
    phone,
    dingzhi_type,
    dingzhi_order_sn,
    bartender_id,
    is_needs_questionnaire,
  } = baseForm.value;

  if (!username) flag = false;
  if (!phone) flag = false;
  if (!dingzhi_type) flag = false;
  if (!bartender_id) flag = false;
  if (dingzhi_type == 1) {
    baseForm.value.dingzhi_order_id = null;
    baseForm.value.dingzhi_order_sn = null;
    baseForm.value.is_needs_questionnaire = null;
  }
  if (dingzhi_type == 2) {
    baseForm.value.is_needs_questionnaire = null;
    if (!dingzhi_order_sn) flag = false;
  }
  if (dingzhi_type == 3) {
    baseForm.value.dingzhi_order_id = null;
    baseForm.value.dingzhi_order_sn = null;
    if (![0, 1].includes(is_needs_questionnaire)) flag = false;
  }
  return flag;
};

onUnload(() => {
  uni.$off("chooseOrder");
});

// 暴露方法给父组件
defineExpose({
  openDialog,
  closeDialog,
});
</script>

<style lang="scss" scoped>
.ask-dialog {
  width: 680rpx;
  background: #fff;
  border-radius: 20rpx;
  height: 80vh;
  overflow-y: auto;
  padding-bottom: 30rpx;
}

.dialog-title {
  font-size: 46rpx;
  margin-bottom: 20rpx;
  text-align: left;
  color: #000;
}
.form-tip {
  font-size: 26rpx;
  line-height: 40rpx;
  color: #999;
}
.label {
  font-size: 34rpx;
  color: #3d3d3d;
}
uni-picker,
picker {
  width: 100%;
}
.picker-disabled {
  flex: 1;
  height: 152rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  padding: 32rpx;
  color: #666;
  align-items: center;
  display: flex;
  box-sizing: border-box;
  transition: all 0.3s;
}

.collapse-title {
  font-weight: 700;
  font-size: 18px;
  color: #3d3d3d;
  position: relative;
  padding-left: 20px;
  &::before {
    content: "";
    position: absolute;
    left: 0;
    top: 12px;
    border-radius: 50%;
    width: 6px;
    height: 6px;
    background: #f00;
  }
}

.top {
  margin: 50rpx 40rpx 20rpx;
}

.submit-btn {
  width: 96%;
  background: #ff0000;
  color: #fff;
  font-size: 30rpx;
  border-radius: 12rpx;
  padding: 8rpx 0;
  border: none;
  margin-top: 30rpx;
}

.submit-btn:disabled {
  background: #f5bdbd;
  color: #fff;
}
.redline {
  border: 2rpx solid red;
}
</style>
